/**
 * 炼焦大数据智能诊断系统
 * 主要JS脚本文件
 */

// 当文档加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面功能
    initNavigation();
    initAnimations();
    initSearchFunction();
    
    // 如果存在相应元素，初始化特定功能
    if (document.querySelector('.particle-container')) {
        initParticleEffect();
    }
    
    if (document.querySelector('.tech-icons')) {
        initTechStackHover();
    }
    
    // 添加滚动事件监听
    initScrollEffects();
    
    // 初始化页面交互
    initInteractions();

    // 图片懒加载
    const lazyImages = document.querySelectorAll('img[data-src]');
    
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.add('loaded');
                    observer.unobserve(img);
                }
            });
        }, {
            rootMargin: '50px 0px',
            threshold: 0.01
        });

        lazyImages.forEach(img => imageObserver.observe(img));
    } else {
        // 兼容性处理
        lazyImages.forEach(img => {
            img.src = img.dataset.src;
            img.classList.add('loaded');
        });
    }

    // 性能优化：防抖和节流
    function debounce(func, wait = 20, immediate = true) {
        let timeout;
        return function() {
            const context = this, args = arguments;
            const later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }

    // 可访问性增强
    function enhanceAccessibility() {
        // 为所有交互元素添加键盘导航支持
        const interactiveElements = document.querySelectorAll('a, button, input, select, textarea');
        interactiveElements.forEach(el => {
            el.addEventListener('keydown', function(e) {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    this.click();
                }
            });
        });

        // 跳过导航链接
        const skipLink = document.createElement('a');
        skipLink.href = '#main-content';
        skipLink.textContent = '跳过导航';
        skipLink.classList.add('skip-link');
        skipLink.style.cssText = `
            position: absolute;
            top: -40px;
            left: 0;
            background: #000;
            color: white;
            padding: 10px;
            z-index: 100;
            transition: top 0.3s;
        `;
        skipLink.addEventListener('focus', function() {
            this.style.top = '0';
        });
        skipLink.addEventListener('blur', function() {
            this.style.top = '-40px';
        });
        document.body.insertBefore(skipLink, document.body.firstChild);
    }

    enhanceAccessibility();

    // 性能监控
    if ('performance' in window) {
        window.addEventListener('load', function() {
            const timing = window.performance.timing;
            const loadTime = timing.loadEventEnd - timing.navigationStart;
            console.log(`页面加载耗时: ${loadTime}ms`);
        });
    }

    // 性能和交互体验优化

    // 资源预加载管理
    resourcePreloader();

    // 性能监控和错误追踪
    performanceMonitoring();

    // 网络状态监控
    networkStatusMonitor();

    // 高级交互优化
    advancedInteractions();
});

/**
 * 初始化导航功能
 */
function initNavigation() {
    // 响应式导航切换
    const navToggle = document.getElementById('navToggle');
    if (navToggle) {
        navToggle.addEventListener('click', function() {
            const navList = document.querySelector('nav ul');
            navList.classList.toggle('active');
            this.classList.toggle('active');
        });
    }
    
    // 滚动时导航栏效果
    window.addEventListener('scroll', function() {
        const nav = document.querySelector('nav');
        if (window.scrollY > 50) {
            nav.classList.add('scrolled');
        } else {
            nav.classList.remove('scrolled');
        }
    });
    
    // 平滑滚动到锚点
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('href');
            if (targetId === '#') return;
            
            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                window.scrollTo({
                    top: targetElement.offsetTop - 80,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // 添加当前页面活动状态
    const currentLocation = window.location.pathname;
    const navLinks = document.querySelectorAll('nav a');
    
    navLinks.forEach(link => {
        const linkPath = link.getAttribute('href');
        if(currentLocation.includes(linkPath) && linkPath !== 'index.html') {
            link.classList.add('active');
        } else if(currentLocation.endsWith('/') && linkPath === 'index.html') {
            link.classList.add('active');
        }
    });
}

/**
 * 初始化动画效果
 */
function initAnimations() {
    // 使用IntersectionObserver监测元素进入视口
    const fadeElements = document.querySelectorAll('.fade-in:not(.delay-1):not(.delay-2):not(.delay-3):not(.delay-4):not(.delay-5)');
    const fadeElementsDelayed1 = document.querySelectorAll('.fade-in.delay-1');
    const fadeElementsDelayed2 = document.querySelectorAll('.fade-in.delay-2');
    const fadeElementsDelayed3 = document.querySelectorAll('.fade-in.delay-3');
    const fadeElementsDelayed4 = document.querySelectorAll('.fade-in.delay-4');
    const fadeElementsDelayed5 = document.querySelectorAll('.fade-in.delay-5');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.style.animationPlayState = 'running';
                observer.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    });
    
    // 设置动画初始状态为暂停
    const setupElements = (elements) => {
        elements.forEach(el => {
            el.style.animationPlayState = 'paused';
            observer.observe(el);
        });
    };
    
    // 应用到所有元素
    setupElements(fadeElements);
    setupElements(fadeElementsDelayed1);
    setupElements(fadeElementsDelayed2);
    setupElements(fadeElementsDelayed3);
    setupElements(fadeElementsDelayed4);
    setupElements(fadeElementsDelayed5);
    
    // 图表加载动画
    const graphContainers = document.querySelectorAll('.graph-container');
    
    const graphObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.classList.add('graph-loaded');
                }, 300);
                graphObserver.unobserve(entry.target);
            }
        });
    }, {
        threshold: 0.1
    });
    
    graphContainers.forEach(container => {
        graphObserver.observe(container);
    });
    
    // 浮动动画优化
    const floatingElements = document.querySelectorAll('.floating');
    floatingElements.forEach((element, index) => {
        // 添加不同的动画延迟，使动画更自然
        const delay = index * 0.2;
        element.style.animationDelay = `${delay}s`;
        // 调整动画时长，使其更加平缓
        element.style.animationDuration = '4s';
    });
}

/**
 * 初始化搜索功能
 */
function initSearchFunction() {
    const searchInput = document.querySelector('.search-input');
    if (searchInput) {
        searchInput.addEventListener('focus', function() {
            this.parentElement.classList.add('active');
        });
        
        searchInput.addEventListener('blur', function() {
            this.parentElement.classList.remove('active');
        });
        
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                // 实现搜索功能
                alert('搜索功能：' + this.value);
                this.value = '';
            }
        });
    }
}

/**
 * 初始化粒子效果
 */
function initParticleEffect() {
    const hero = document.querySelector('.hero');
    const particles = document.querySelectorAll('.particle');
    
    if (hero && particles.length > 0) {
        hero.addEventListener('mousemove', function(e) {
            const rect = hero.getBoundingClientRect();
            const x = (e.clientX - rect.left) / rect.width;
            const y = (e.clientY - rect.top) / rect.height;
            
            particles.forEach(particle => {
                const speed = parseFloat(particle.style.opacity) * 30;
                const offsetX = (x - 0.5) * speed;
                const offsetY = (y - 0.5) * speed;
                
                particle.style.transform = `translate(${offsetX}px, ${offsetY}px)`;
            });
        });
        
        hero.addEventListener('mouseleave', function() {
            particles.forEach(particle => {
                particle.style.transform = 'translate(0, 0)';
                particle.style.transition = 'transform 0.5s ease-out';
            });
        });
    }
}

/**
 * 初始化技术栈悬停效果
 */
function initTechStackHover() {
    const techIcons = document.querySelectorAll('.tech-icon');
    
    techIcons.forEach(icon => {
        icon.addEventListener('mouseenter', function() {
            this.classList.add('hover-scale');
            this.style.zIndex = 10;
        });
        
        icon.addEventListener('mouseleave', function() {
            this.classList.remove('hover-scale');
            this.style.zIndex = 1;
        });
    });
}

/**
 * 页面滚动进度指示器
 */
function initScrollProgress() {
    const progressBar = document.createElement('div');
    progressBar.className = 'scroll-progress';
    document.body.appendChild(progressBar);
    
    window.addEventListener('scroll', function() {
        const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
        const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrolled = (winScroll / height) * 100;
        progressBar.style.width = scrolled + '%';
    });
}

/**
 * 工具函数：防抖
 */
function debounce(func, wait = 20, immediate = true) {
    let timeout;
    return function() {
        const context = this, args = arguments;
        const later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
}

// 滚动效果初始化
function initScrollEffects() {
    // 页面滚动到顶部按钮
    const scrollTopBtn = document.createElement('button');
    scrollTopBtn.classList.add('scroll-top-btn');
    scrollTopBtn.innerHTML = '<i class="fas fa-arrow-up"></i>';
    document.body.appendChild(scrollTopBtn);
    
    scrollTopBtn.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 500) {
            scrollTopBtn.classList.add('visible');
        } else {
            scrollTopBtn.classList.remove('visible');
        }
    });
}

// 页面交互初始化
function initInteractions() {
    // 标签页切换
    const tabButtons = document.querySelectorAll('.tab-btn');
    
    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            // 移除所有活动状态
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            
            // 添加当前活动状态
            this.classList.add('active');
            const tabId = this.dataset.tab;
            document.getElementById(tabId).classList.add('active');
        });
    });
    
    // 添加按钮波纹效果
    const rippleButtons = document.querySelectorAll('.btn-effect, .ripple-effect');
    
    rippleButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            const rect = this.getBoundingClientRect();
            const x = e.clientX - rect.left;
            const y = e.clientY - rect.top;
            
            const ripple = document.createElement('span');
            ripple.classList.add('ripple');
            ripple.style.left = `${x}px`;
            ripple.style.top = `${y}px`;
            
            this.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });
    
    // 动态数字增长效果
    const counterElements = document.querySelectorAll('.counter');
    
    const counterObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const counter = entry.target;
                const target = parseInt(counter.getAttribute('data-target'));
                const duration = 2000; // 2秒完成动画
                const step = target / (duration / 16); // 每16ms增加的数量
                
                let current = 0;
                const timer = setInterval(() => {
                    current += step;
                    counter.textContent = Math.round(current);
                    
                    if (current >= target) {
                        counter.textContent = target;
                        clearInterval(timer);
                    }
                }, 16);
                
                counterObserver.unobserve(counter);
            }
        });
    }, {
        threshold: 0.5
    });
    
    counterElements.forEach(counter => {
        counterObserver.observe(counter);
    });
}

// 添加CSS样式
const style = document.createElement('style');
style.innerHTML = `
    .scroll-top-btn {
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background-color: var(--primary-color);
        color: white;
        border: none;
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
        z-index: 99;
        opacity: 0;
        transform: translateY(20px);
        transition: all 0.3s ease;
        pointer-events: none;
    }
    
    .scroll-top-btn.visible {
        opacity: 1;
        transform: translateY(0);
        pointer-events: auto;
    }
    
    .scroll-top-btn:hover {
        background-color: var(--primary-dark);
        transform: translateY(-5px);
    }
    
    .ripple {
        position: absolute;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.7);
        transform: scale(0);
        animation: ripple-effect 0.6s linear;
        pointer-events: none;
    }
    
    @keyframes ripple-effect {
        to {
            transform: scale(4);
            opacity: 0;
        }
    }
    
    /* 添加平滑滚动 */
    html {
        scroll-behavior: smooth;
    }
    
    /* 改进Tab切换动画 */
    .tab-content {
        opacity: 0;
        transform: translateY(10px);
        transition: all 0.3s ease;
        height: 0;
        overflow: hidden;
    }
    
    .tab-content.active {
        opacity: 1;
        transform: translateY(0);
        height: auto;
        overflow: visible;
    }
`;

document.head.appendChild(style);

// 动态粒子背景效果
function createParticleBackground() {
    const canvas = document.createElement('canvas');
    const heroBackground = document.querySelector('.page-header-bg');
    
    if (!heroBackground) return;
    
    heroBackground.appendChild(canvas);
    canvas.style.position = 'absolute';
    canvas.style.top = '0';
    canvas.style.left = '0';
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.zIndex = '-1';
    
    const ctx = canvas.getContext('2d');
    canvas.width = heroBackground.clientWidth;
    canvas.height = heroBackground.clientHeight;
    
    const particles = [];
    const particleCount = 50;
    
    class Particle {
        constructor() {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;
            this.radius = Math.random() * 3 + 1;
            this.speedX = Math.random() * 1 - 0.5;
            this.speedY = Math.random() * 1 - 0.5;
            this.color = `rgba(255, 255, 255, ${Math.random() * 0.3 + 0.1})`;
        }
        
        draw() {
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
            ctx.fillStyle = this.color;
            ctx.fill();
            ctx.closePath();
        }
        
        update() {
            this.x += this.speedX;
            this.y += this.speedY;
            
            if (this.x < 0 || this.x > canvas.width) this.speedX *= -1;
            if (this.y < 0 || this.y > canvas.height) this.speedY *= -1;
        }
    }
    
    function init() {
        for (let i = 0; i < particleCount; i++) {
            particles.push(new Particle());
        }
    }
    
    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        particles.forEach(particle => {
            particle.draw();
            particle.update();
        });
        
        requestAnimationFrame(animate);
    }
    
    init();
    animate();
    
    window.addEventListener('resize', () => {
        canvas.width = heroBackground.clientWidth;
        canvas.height = heroBackground.clientHeight;
    });
}

document.addEventListener('DOMContentLoaded', createParticleBackground);

// 资源预加载管理
function resourcePreloader() {
    const resources = [
        '../styles/main.css',
        '../styles/page.css',
        '../images/hero-background.svg',
        '../images/logo.png'
    ];

    if ('link' in document.createElement('link')) {
        resources.forEach(resource => {
            const link = document.createElement('link');
            link.rel = 'preload';
            link.href = resource;
            link.as = resource.endsWith('.css') ? 'style' : 
                      resource.endsWith('.png') ? 'image' : 
                      resource.endsWith('.svg') ? 'image' : 'fetch';
            document.head.appendChild(link);
        });
    }
}

// 性能监控和错误追踪
function performanceMonitoring() {
    // 页面加载性能追踪
    if ('performance' in window) {
        const perfEntries = performance.getEntriesByType("navigation")[0];
        const metrics = {
            dns: perfEntries.domainLookupEnd - perfEntries.domainLookupStart,
            tcp: perfEntries.connectEnd - perfEntries.connectStart,
            ttfb: perfEntries.responseStart - perfEntries.requestStart,
            download: perfEntries.responseEnd - perfEntries.responseStart,
            processingTime: perfEntries.domComplete - perfEntries.domLoading
        };

        console.group('页面性能指标');
        Object.entries(metrics).forEach(([key, value]) => {
            console.log(`${key}: ${value}ms`);
        });
        console.groupEnd();
    }

    // 错误追踪
    window.addEventListener('error', function(event) {
        console.error('捕获到错误:', {
            message: event.message,
            filename: event.filename,
            lineno: event.lineno,
            colno: event.colno,
            error: event.error
        });
    });
}

// 网络状态监控
function networkStatusMonitor() {
    const statusIndicator = document.createElement('div');
    statusIndicator.id = 'network-status';
    statusIndicator.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        padding: 10px;
        background-color: #333;
        color: white;
        border-radius: 5px;
        z-index: 9999;
        display: none;
    `;
    document.body.appendChild(statusIndicator);

    function updateNetworkStatus() {
        if (navigator.onLine) {
            statusIndicator.textContent = '网络已连接';
            statusIndicator.style.backgroundColor = '#4CAF50';
            statusIndicator.style.display = 'block';
            setTimeout(() => {
                statusIndicator.style.display = 'none';
            }, 3000);
        } else {
            statusIndicator.textContent = '网络已断开';
            statusIndicator.style.backgroundColor = '#F44336';
            statusIndicator.style.display = 'block';
        }
    }

    window.addEventListener('online', updateNetworkStatus);
    window.addEventListener('offline', updateNetworkStatus);
}

// 高级交互优化
function advancedInteractions() {
    // 智能滚动进度
    const progressBar = document.createElement('div');
    progressBar.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 0;
        height: 3px;
        background: linear-gradient(to right, #2563eb, #60a5fa);
        z-index: 9999;
        transition: width 0.2s ease;
    `;
    document.body.appendChild(progressBar);

    window.addEventListener('scroll', () => {
        const winScroll = document.body.scrollTop || document.documentElement.scrollTop;
        const height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        const scrolled = (winScroll / height) * 100;
        progressBar.style.width = `${scrolled}%`;
    });

    // 智能焦点管理
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Tab') {
            document.body.classList.add('user-is-tabbing');
        }
    });

    document.addEventListener('mousedown', function() {
        document.body.classList.remove('user-is-tabbing');
    });
}

// 初始化所有优化功能
function initOptimizations() {
    resourcePreloader();
    performanceMonitoring();
    networkStatusMonitor();
    advancedInteractions();
}

// 在DOM加载完成后执行
document.addEventListener('DOMContentLoaded', initOptimizations); 